<template>
  <div class="payment-page">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>订单支付</h1>
    </div>

    <!-- 主内容区 - 两栏布局 -->
    <div class="main-content">
      <!-- 左侧 - 商品详情 -->
      <div class="left-column">
        <div class="order-info" v-if="orderLoaded">
          <span class="order-id">订单号：{{ order.orderId }}</span>
          <el-table :data="order.goodsList" style="width: 100%; margin-top: 20px;">
            <el-table-column prop="imagePathList" label="商品图片" width="100">
              <template #default="scope">
                <img :src="getPath(scope.row.imagePathList[0])" class="product-image" />
              </template>
            </el-table-column>
            <el-table-column prop="name" label="商品名称" />
            <el-table-column prop="price" label="单价" width="100">
              <template #default="scope">¥{{ scope.row.price }}</template>
            </el-table-column>
            <el-table-column prop="count" label="数量" width="80" />
            <el-table-column prop="totalAmount" label="小计" width="100">
              <template #default="scope">¥{{ scope.row.totalAmount }}</template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <!-- 右侧 - 付款详情 -->
      <div class="right-column">
        <div class="payment-summary" v-if="orderLoaded">
          <h3 class="summary-title">付款详情</h3>

          <!-- 价格信息 -->
          <div class="price-info">
            <div class="price-item">
              <span>商品总价：</span>
              <span class="price-value">¥{{ originalTotalAmount }}</span>
            </div>

            <!-- 优惠券选择 - 仅显示立减券 -->
            <div class="coupon-select">
              <span>优惠券：</span>
              <el-select v-model="selectedCouponId" placeholder="请选择立减券" style="width: 180px;" @change="applyCoupon">
                <el-option v-for="coupon in couponList" :key="coupon.id" :label="coupon.couponName" :value="coupon.id">
                  <span>{{ coupon.couponName }}</span>
                  <span class="coupon-discount">
                    立减¥{{ coupon.amount }}
                  </span>
                </el-option>
                <el-option value="0" label="不使用优惠券" />
              </el-select>
            </div>

            <!-- 修改这里的条件判断，使用selectedCouponId > 0而不是selectedCoupon -->
            <div class="price-item" v-if="selectedCouponId > 0">
              <span>优惠券优惠：</span>
              <span class="price-discount">-¥{{ selectedCoupon ? selectedCoupon.amount : 0 }}</span>
            </div>

            <div class="price-item total-price">
              <span>应付金额：</span>
              <span class="price-value total-amount">¥{{ discountedTotalAmount }}</span>
            </div>

          </div>

          <!-- 支付方式 -->
          <div class="payment-methods">
            <h4 class="method-title">支付方式</h4>
            <div class="payment-options">
              <el-radio-group v-model="paymentMethod">
                <el-radio-button  label="balance">余额支付</el-radio-button>
                <el-radio-button label="wechat">微信支付</el-radio-button>
                <el-radio-button label="alipay">支付宝</el-radio-button>
              </el-radio-group>
            </div>

            <!-- 余额不足提示 -->
            <div v-if="paymentMethod === 'balance' && userBalance < discountedTotalAmount" class="balance-warning">
              <el-tag type="warning">您的余额不足，建议选择其他支付方式</el-tag>
            </div>
          </div>

          <!-- 支付按钮 -->
          <div class="pay-button-container">
            <el-button class="bn2" type="primary" :disabled="!paymentMethod" @click="handlePayment">
              确认支付 ¥{{ discountedTotalAmount }}
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 余额支付密码弹窗 -->
    <el-dialog v-model="showPasswordDialog" title="余额支付" width="30%">
      <el-form :model="paymentForm" label-width="150px">
        <el-form-item label="支付密码(同用户密码)">
          <el-input v-model="paymentForm.password" type="password" show-password />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showPasswordDialog = false">取消</el-button>
          <el-button class="confirm"  @click="confirmPassword">确认支付</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter, useRoute } from 'vue-router';
import { get, post } from '@/plugins/axios';
import { getPath } from '@/util';
import { getCookieForObject } from '@/util';

// 路由相关
const router = useRouter();
const route = useRoute();

// 状态管理
const orderLoaded = ref(false);
const order = ref(null);
const couponList = ref([]);
const selectedCouponId = ref(0); // 默认为0表示不使用优惠券
const paymentMethod = ref('balance');
const showPasswordDialog = ref(false);
const paymentForm = reactive({
  password: ''
});

// 用户信息
const userInfo = getCookieForObject('user');
const userBalance = computed(() => parseFloat(userInfo?.account || 0));

// 获取选中的优惠券
const selectedCoupon = computed(() => {
  if (selectedCouponId.value === 0) return null;
  return couponList.value.find(coupon => coupon.id === selectedCouponId.value);
});

// 商品总价
const originalTotalAmount = computed(() => {
  if (!order.value || !order.value.totalAmount) return '0.00';
  return parseFloat(order.value.totalAmount).toFixed(2);
});

// 应付金额（优化后的计算逻辑）
const discountedTotalAmount = computed(() => {
  console.log('计算应付金额，依赖更新');

  // 处理原始金额不存在的情况
  if (!order.value || !order.value.totalAmount) {
    return '0.00';
  }

  const total = parseFloat(order.value.totalAmount);
  const isUsingCoupon = selectedCouponId.value > 0;

  // 获取优惠券折扣
  let discount = 0;
  if (isUsingCoupon && selectedCoupon.value) {
    discount = selectedCoupon.value.amount;
    console.log('使用优惠券折扣:', discount);
  }

  // 计算应付金额
  const result = total - discount;
  console.log('应付金额计算结果:', result);
  return (result < 0 ? 0 : result).toFixed(2);
});

// 工具函数
// const getCouponDiscountText = (coupon) => {
//   return `立减${coupon.amount}元`;
// };

// 获取订单详情
const fetchOrderDetail = () => {
  get('/orders/getById', { orderId: route.query.id }, (data) => {
    if (data) {
      order.value = data;
      orderLoaded.value = true;
      fetchUserCoupons();
    } else {
      ElMessage.error('获取订单信息失败');
      router.push('/order-list');
    }
  });
};

// 获取用户可用立减券
const fetchUserCoupons = () => {
  if (!userInfo) return;
  get('/coupon/user', { userId: userInfo.id }, (coupons) => {
    couponList.value = coupons || [];
    // 自动选择第一张可用立减券
    if (coupons.length > 0) {
      selectedCouponId.value = coupons[0].id;
    } else {
      selectedCouponId.value = 0;
    }
  });
};

// 应用优惠券
const applyCoupon = () => {
  console.log('选择优惠券ID:', selectedCouponId.value);

  // 触发计算属性更新
  if (discountedTotalAmount.value) {
    discountedTotalAmount.value; // 强制访问计算属性
  }

  if (selectedCouponId.value === 0) {
    ElMessage({
      message: '已选择不使用优惠券',
      type: 'info',
    });
  } else if (selectedCoupon.value) {
    ElMessage({
      message: `已选择优惠券: ${selectedCoupon.value.couponName}`,
      type: 'info',
    });
  }
};

// 处理支付
const handlePayment = () => {
  if (paymentMethod.value === 'balance') {
    if (userBalance.value < parseFloat(discountedTotalAmount.value)) {
      ElMessageBox.confirm(
          '您的余额不足，是否前往充值？',
          '提示',
          {
            confirmButtonText: '前往充值',
            cancelButtonText: '取消',
            type: 'warning'
          }
      ).then(() => {
        router.push('/recharge-transfer');
      });
      return;
    }
    showPasswordDialog.value = true;
  } else {
    // 微信/支付宝支付逻辑
    ElMessage({
      message: `即将跳转到${paymentMethod.value === 'wechat' ? '微信' : '支付宝'}支付`,
      type: 'info',
    });
  }
};

// 确认支付密码
const confirmPassword = () => {
  if (!paymentForm.password) {
    ElMessage.error('请输入支付密码');
    return;
  }

  // 调用支付接口，传递couponId
  post('/orders/payTheOrder', {
    password: paymentForm.password,
    orderId: order.value.id,
    userId: userInfo.id,
    couponId: selectedCouponId.value
  }, (res) => {
    showPasswordDialog.value = false;

    if (res) {
      // 更新用户余额
      const newBalance = (userBalance.value - parseFloat(discountedTotalAmount.value)).toFixed(2);
      userInfo.account = newBalance;
      //setCookiesFromObject('user', userInfo);

      router.push('/pay-success');
    } else {
      ElMessage.error(res.message || '支付失败，请检查支付密码');
    }
  });
};

// 组件挂载时加载数据
onMounted(() => {
  fetchOrderDetail();
});
</script>

<style lang="scss" scoped>
.payment-page {
  padding: 20px;

  .page-header {
    text-align: center;
    margin-bottom: 30px;

    h1 {
      font-size: 24px;
      color: #333;
      margin: 0;
    }
  }

  .main-content {
    display: flex;
    gap: 20px;

    .left-column, .right-column {
      flex: 1;
    }

    .left-column {
      background-color: #fff;
      border-radius: 8px;
      padding: 20px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    }

    .right-column {
      background-color: #fff;
      border-radius: 8px;
      padding: 20px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    }
  }

  .order-id {
    font-weight: bold;
    color: #ec880b;
  }

  .product-image {
    width: 60px;
    height: 60px;
    object-fit: cover;
    border-radius: 4px;
  }

  .summary-title, .method-title {
    font-size: 18px;
    margin-top: 0;
    padding-bottom: 10px;
    border-bottom: 1px solid #ebeef5;
    margin-bottom: 20px;
  }

  .price-info {
    margin-bottom: 30px;

    .price-item {
      display: flex;
      justify-content: space-between;
      padding: 10px 0;
      border-bottom: 1px solid #ebeef5;

      &.total-price {
        font-weight: bold;
        font-size: 18px;
        color: #f5816c;
        border-bottom: none;
      }

      .price-value {
        font-weight: normal;
      }

      .price-discount {
        color: #f56c6c;
      }
    }
  }

  .coupon-select {
    margin: 15px 0;
  }

  .coupon-discount {
    color: #ff6b6b;
    margin-left: 10px;
    font-size: 14px;
  }

  .payment-methods {
    margin-bottom: 30px;

    .payment-options {
      display: flex;
      gap: 20px;
      margin-top: 10px;

    }
  }

  .balance-warning {
    margin-top: 10px;
  }

  .pay-button-container {
    margin-top: 30px;
    text-align: center;
  }
  .confirm{
    background-color: #f69b29;
    color: #fafafa;
  }
  .bn2{
    background-color: #fa9820;
    border: #9f5b07;
  }
  .bn2:hover{
    background-color: #f6e0c6;
    border: #9f5b07;
    color: #a15c07;
  }

}
</style>